﻿using ML.Entity;
using ML.IBusiness;
using ML.IRepository;
using ML.Utils;
using System.Linq;
using System;

namespace ML.Business
{
    /// <summary>
    /// 用户业务实现类
    /// </summary>
    public class UserBusiness : IUserBusiness
    {
        private readonly IUserRepository userRepository;
        private readonly IMerchantRepository merchantRepository;
        private readonly IOrderRepository orderRepository;
        public UserBusiness(IUserRepository _userRepository, IMerchantRepository _merchantRepository, IOrderRepository _orderRepository)
        {
            userRepository = _userRepository;
            merchantRepository = _merchantRepository;
            orderRepository = _orderRepository;
        }

        public BaseResult<Pager<UserEntity>> List(UserSearch userSearch)
        {
            //根据传递的条件查询
            Pager<UserEntity> data = userRepository.List(userSearch);
            return new BaseResult<Pager<UserEntity>>(200, data);
        }

        public BaseResult<UserEntity> GetById(string id)
        {
            var data = userRepository.GetById(id);
            data.Password = "";
            return new BaseResult<UserEntity>(200, data);
        }

        public BaseResult<WXuserLogin> WXgetById(string id)
        {
            var data = userRepository.GetById(id);
            if (data==null)
            {
                return new BaseResult<WXuserLogin>(1001, null);
            }
            data.Password = "";
            return new BaseResult<WXuserLogin>(200, new WXuserLogin { LoginCode = data.Id, UserName = data.UserName });
        }

        public BaseResult<UserEntity> GetByUserId(string id)
        {
            var data = userRepository.GetById(id);
            if (data == null)
            {
                return new BaseResult<UserEntity>(202);
            }
            data.Password = "";
            if (data.DelMark == (int)DeleteStatus.delete_true)
            {
                return new BaseResult<UserEntity>(1003);
            }
            return new BaseResult<UserEntity>(200, data);
        }

        public BaseResult<UserEntity> GetByOpenId(string id)
        {
            var data = userRepository.GetByOpenId(id);
            if (data == null)
            {
                return new BaseResult<UserEntity>(202);
            }
            data.Password = "";
            if (data.DelMark == (int)DeleteStatus.delete_true)
            {
                return new BaseResult<UserEntity>(1003);
            }
            return new BaseResult<UserEntity>(200, data);
        }

        public BaseResult<bool> Login(string login_name_in, string user_pwd_in)
        {
            if (string.IsNullOrEmpty(login_name_in) || string.IsNullOrEmpty(user_pwd_in))
            {
                return new BaseResult<bool>(800, false);
            }

            //根据用户名和密码对查询用户信息
            var userEntity = userRepository.Login(login_name_in, CommonUtil.Md5(user_pwd_in));
            if (userEntity == null)
            {
                return new BaseResult<bool>(1000, false);
            }

            //判断如果用户是商户，则需要查询商户的Id和名称存储在Session中

            UserInfoSession userInfo = new UserInfoSession();
            if (userEntity.UserType == (int)UserTypeStatus.merchant)
            {
                var entity = merchantRepository.GetInfoByUserId(userEntity.Id);
                if (entity != null)
                {
                    userInfo.MerchantId = entity.Id;
                    userInfo.MerchantName = entity.Name;
                }
                else
                {
                    userInfo.MerchantId = "";
                    userInfo.MerchantName = "";
                }
            }
            userInfo.UserId = userEntity.Id;
            userInfo.UserName = userEntity.UserName;
            userInfo.NickName = userEntity.NickName;
            userInfo.Tel = userEntity.Tel;
            userInfo.OpenId = userEntity.OpenId;
            userInfo.UserType = userEntity.UserType;
            userInfo.PhotoGraph = userEntity.PhotoGraph;

            //将查询到的结果存放到Session中并且返回成功标示
            UserHelper.SetSession(userInfo);
            return new BaseResult<bool>(200, true);
        }

        public BaseResult<bool> HorsemanLogin(string nickname, string password)
        {
            if (string.IsNullOrEmpty(nickname) || string.IsNullOrEmpty(password))
            {
                return new BaseResult<bool>(800, false);
            }

            //根据用户名和密码对查询用户信息
            var userEntity = userRepository.Login(nickname, CommonUtil.Md5(password));
            if (userEntity == null || userEntity.UserType != (int)UserTypeStatus.horseman)
            {
                return new BaseResult<bool>(1000, false);
            }
            return new BaseResult<bool>(200, true);
        }

        public BaseResult<bool> MerchantLogin(string nickname, string password)
        {
            if (string.IsNullOrEmpty(nickname) || string.IsNullOrEmpty(password))
            {
                return new BaseResult<bool>(800, false);
            }

            //根据用户名和密码对查询用户信息
            var userEntity = userRepository.Login(nickname, CommonUtil.Md5(password));
            if (userEntity == null || userEntity.UserType != (int)UserTypeStatus.merchant)
            {
                return new BaseResult<bool>(1000, false);
            }
            return new BaseResult<bool>(200, true);
        }

        /// <summary>
        /// 商户登录api接口（微信小程序）
        /// </summary>
        /// <param name="nickname"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public BaseResult<WXuserLogin> WXmerchantLogin(string nickname, string password)
        {
            var userLogin = new WXuserLogin();
            //根据用户名和密码对查询用户信息
            var userEntity = userRepository.Login(nickname, CommonUtil.Md5(password));
            if (userEntity == null || userEntity.UserType != (int)UserTypeStatus.merchant)
            {
                return new BaseResult<WXuserLogin>(1000, null);
            }
            userLogin.LoginCode = userEntity.Id;
            userLogin.UserName = userEntity.UserName;
            return new BaseResult<WXuserLogin>(200, userLogin);
        }

        public BaseResult<bool> Add(UserEntity userEntity)
        {
            userEntity.Password = CommonUtil.Md5(userEntity.Password);
            userEntity.InvitationCode = CommonUtil.ReadDateTime() + CommonUtil.LiterNumberReadRandom(3);
            bool isTrue = userRepository.Add(userEntity);
            return new BaseResult<bool>(isTrue);
        }

        public BaseResult<UserEntity> AddWXUser(UserEntity userEntity)
        {
            //根据OpenId查询用户信息(如果用户存在直接返回,否则查询)
            UserEntity userinfo = userRepository.GetByOpenId(userEntity.OpenId);
            if (userinfo != null)
            {
                return new BaseResult<UserEntity>(200, userinfo);
            }

            //判断邀请码是否为空(邀请码为空直接插入用于表即可，否则需要插入关联表信息)
            if (string.IsNullOrEmpty(userEntity.InvitationCode))
            {
                userEntity.Id = CommonUtil.CreateGuid();
                userEntity.Password = CommonUtil.Md5("888888");
                userEntity.InvitationCode = CommonUtil.ReadDateTime() + CommonUtil.LiterNumberReadRandom(3);
                var isTrue = userRepository.Add(userEntity);
                if (isTrue)
                {
                    userEntity.Password = "";
                    return new BaseResult<UserEntity>(200, userEntity);
                }
                else
                {
                    return new BaseResult<UserEntity>(201);
                }
            }
            else
            {
                string invitationcode_params = userEntity.InvitationCode;
                userEntity.InvitationCode = CommonUtil.ReadDateTime() + CommonUtil.LiterNumberReadRandom(3);

                //根据邀请码信息查询用户信息，用户是唯一的
                UserEntity userEntityExtension = userRepository.getByInvitationCode(invitationcode_params);

                //组装用户邀请表实体信息
                var userInvitationEntity = new UserInvitationEntity()
                {
                    InvitationId = userEntityExtension.Id,
                    BeInvitationId = userEntity.Id,
                    AddType = "邀请链接",
                    ContentSource = invitationcode_params,
                };

                var isTrue = userRepository.AddUser(userEntity, userInvitationEntity);
                if (isTrue)
                {
                    userEntity.Password = "";
                    return new BaseResult<UserEntity>(200, userEntity);
                }
                return new BaseResult<UserEntity>(201);
            }
        }

        public BaseResult<bool> UpdateUser(UserEntity userEntity)
        {
            var isTrue = userRepository.UpdateUser(userEntity);
            if (isTrue)
            {
                return new BaseResult<bool>(200, true);
            }
            return new BaseResult<bool>(201, false);
        }

        public BaseResult<bool> UpdatePassword(string id, string password_new)
        {
            UserEntity userEntity = userRepository.GetById(id);
            if (userEntity == null)
            {
                return new BaseResult<bool>(1001, false);
            }
            if (userEntity.DelMark == (int)DeleteStatus.delete_true)
            {
                return new BaseResult<bool>(1003, false);
            }

            //符合修改更新密码
            userEntity.Password = CommonUtil.Md5(password_new);
            var isTrue = userRepository.Update(userEntity);
            if (isTrue)
            {
                return new BaseResult<bool>(200, true);
            }
            return new BaseResult<bool>(201, false);
        }

        public BaseResult<bool> UpdateUserType(string id, int user_type)
        {
            if (string.IsNullOrEmpty(id))
            {
                return new BaseResult<bool>(1001, false);
            }

            //判断该用户下是否含有商户，如果含有则不允许修改
            var data = merchantRepository.GetInfoByUserId(id);
            if (data != null)
            {
                return new BaseResult<bool>(1005, false);
            }

            UserEntity userEntity = userRepository.GetById(id);
            if (userEntity == null)
            {
                return new BaseResult<bool>(1001, false);
            }

            userEntity.UserType = user_type;
            var isTrue = userRepository.Update(userEntity);
            if (isTrue)
            {
                return new BaseResult<bool>(200, true);
            }
            return new BaseResult<bool>(201, false);
        }

        public BaseResult<bool> Delete(string id)
        {
            if (string.IsNullOrEmpty(id))
            {
                return new BaseResult<bool>(1001, false);
            }

            //查询用户是否已经下订单或者开店，如果已经下订单或者开店则不允许删除此用户
            var orders = orderRepository.GetListByUserId(id);
            if (orders.Count() > 0)
            {
                return new BaseResult<bool>(1006, false);
            }
            var entity = merchantRepository.GetInfoByUserId(id);
            if (entity != null)
            {
                return new BaseResult<bool>(1005, false);
            }

            UserEntity userEntity = userRepository.GetById(id);
            if (userEntity == null)
            {
                return new BaseResult<bool>(1001, false);
            }

            userEntity.DelMark = (int)DeleteStatus.delete_true;
            var isTrue = userRepository.Update(userEntity);
            if (isTrue)
            {
                return new BaseResult<bool>(200, true);
            }
            return new BaseResult<bool>(201, false);
        }

        public BaseResult<UserEntity> GetByInvitationCode(string invitationcode)
        {
            var data = userRepository.getByInvitationCode(invitationcode);
            return new BaseResult<UserEntity>(200, data);
        }

    }
}